package fri.android;

import java.util.List;
import java.util.Vector;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.TextView;

public class Begin extends Activity {
	
	private boolean hasGPS=false;
	private String gpsProvider="GPS_PROVIDER";
	private int minTime=2000;
	private int minDist=0;
	private LocationManager locationManager;
	private LocationListener locationListener;
	private boolean isListenerRegistered;
	private Location currentLocation;
	private int counter=0;
	private Vector<Location> records;
	public TextView locText;
	public Chronometer cm;
	double fullDistance;

	
	public static final String PREFS_NAME = "MyPrefsFile";
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
			
		 
        requestWindowFeature(Window.FEATURE_NO_TITLE);  
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); 
        fullDistance=0;
			
		   SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
	       int backgroundindex=settings.getInt("background"+settings.getInt("activeProf", 1), 3);
	       if(backgroundindex==0){
	        getWindow().setBackgroundDrawable(getResources().getDrawable(R.drawable.back00));
	       }else if(backgroundindex==1){
	        getWindow().setBackgroundDrawable(getResources().getDrawable(R.drawable.back01));
	       }else if(backgroundindex==2){
	        getWindow().setBackgroundDrawable(getResources().getDrawable(R.drawable.back02));
	       }else if(backgroundindex==3){
	        getWindow().setBackgroundDrawable(getResources().getDrawable(R.drawable.back03));
	       }else if(backgroundindex==4){
	        getWindow().setBackgroundDrawable(getResources().getDrawable(R.drawable.back04));
	       }
		
        
        this. records = new Vector<Location>();
        //gumb za prekinitev
        setContentView(R.layout.begin);
        
        final TextView status=(TextView)this.findViewById(R.id.Status);
        locText=(TextView) findViewById(R.id.Location);
        
        status.setText("Loading...");
        
        final Button buttonback2= (Button) findViewById(R.id.ButtonStop);      
        buttonback2.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	
            	
   
            	minTime*=1000;
            	
            	SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
                SharedPreferences.Editor editor = settings.edit();
                editor.putString("fullTime"+settings.getInt("activeProf", 1),((Chronometer) findViewById(R.id.Chronometer01)).getText().toString()); //Begin.this.cm.getText().toString());
                editor.putInt("fullDistance"+settings.getInt("activeProf", 1), (int) Math.round(fullDistance));
                
                editor.commit();
             
            	
            	
            	
            	Begin.this.startActivity(new Intent(Begin.this, Results.class));
         	   	finish();
            }
        });

        //najdemo providerja GPS
        locationManager=(LocationManager) getSystemService(LOCATION_SERVICE);
        
        locationListener=new LocationListener() {			
			public void onStatusChanged(String provider, int status, Bundle extras) {}
			public void onProviderEnabled(String provider) {}
			public void onProviderDisabled(String provider) {} 			
		
			public void onLocationChanged(Location location) {
	
				
				locText.setText(location.getLatitude()+" "+location.getLongitude());
				status.setText("Update nr. "+counter);
				updateLocation(location);
				calcData();
			}
		};
        
    	List<String> providers=locationManager.getProviders(true);
    	
    	if (providers.size()>0) {
    		//ali obstaja GPS
    		for (int i = 0; i<providers.size();i++){
    			if (providers.get(i).equalsIgnoreCase("gps")){
    				this.hasGPS=true;
    				this.gpsProvider=providers.get(i);
    			
    				break;
    			}
    		}
    		//ce ne obstaja vrnemo message
    		if (!hasGPS){
    			status.setText("No GPS HW found...");
    		}
    		status.setText("GPS found...");
    		
    		Chronometer cm=(Chronometer) this.findViewById(R.id.Chronometer01);
    		cm.start();
    		
    				
    		
    		//kreiramo listener
	
    		locationManager.requestLocationUpdates(providers.get(0), 3000, 5, locationListener);
    		
  		
    		
    	} else {
    		status.setText("No LOCATION HW found...");
    	}
    	
	}
	
	public void updateLocation(Location location) {
		counter++;
    	double lat=location.getLatitude();
		double lon=location.getLongitude();
		double alt=location.getAltitude();
		double time=location.getTime();	

		this.records.add(location);
    }
	
	public void calcData(){
		double beginTime=records.elementAt(0).getTime();
		double lastTime=records.elementAt(records.size()-1).getTime();
		
		double time =Math.round((lastTime-beginTime)/(double)(1000));
		if(records.size()>=2){

			double tempDistance=0;
			for(int i=0;i<records.size()-1;i++){
				
				tempDistance = records.get(i).distanceTo(records.get(i+1));
				this.fullDistance=this.fullDistance+tempDistance;
			}
			this.fullDistance=(Math.round(this.fullDistance/5));
			lastTime=records.elementAt(records.size()-1).getTime()-records.elementAt(records.size()-2).getTime();
			double speed=(((double)tempDistance/(double)(lastTime)));
			

			
			TextView distancetext=(TextView)this.findViewById(R.id.TextDistance);
			distancetext.setText("Distance: "+(this.fullDistance)+"m");
			
			TextView speedtext=(TextView)this.findViewById(R.id.TextSpeed);
			speedtext.setText("Speed: "+Math.round(speed*1000)+"m/s");
		}
	}
	
}